from django.db import models

from gis.common.django_ext.models import BaseModel, ListField


class ProConfig(BaseModel):
    name = models.CharField(max_length=100)
    api_key = models.CharField(max_length=100)
    get_data_url = models.CharField(max_length=100)

    class Meta:
        db_table = 'pro_config'


class Role(BaseModel):
    name = models.CharField(max_length=50, unique=True)
    desc = models.CharField(max_length=200, null=True)
    permissions = models.ManyToManyField('Permission', through='RolePermissionRel')


class User(BaseModel):
    name = models.CharField(max_length=50, unique=True)
    password = models.CharField(max_length=100)
    is_super = models.BooleanField(default=False)
    enable = models.BooleanField(default=True)
    role = models.ForeignKey(Role, on_delete=models.CASCADE, null=True)
    deleted = models.BooleanField(default=False)
    pro = models.ForeignKey(ProConfig, on_delete=models.CASCADE, db_constraint=False)
    status = models.IntegerField(null=True, default=0)


class Permission(BaseModel):
    parent = models.ForeignKey('self', on_delete=models.PROTECT, null=True)
    name = models.CharField(max_length=50)
    code = models.CharField(max_length=50, unique=True)
    sort_index = models.IntegerField(default=1)
    desc = models.CharField(max_length=200, null=True)
    full_path = models.CharField(max_length=100)
    is_leaf = models.BooleanField(default=False)
    fields = ListField(max_length=1000, null=True)

    class Meta:
        ordering = ['sort_index']


class RolePermissionRel(BaseModel):
    role = models.ForeignKey(Role, on_delete=models.CASCADE)
    permission = models.ForeignKey(Permission, on_delete=models.CASCADE)
    include_fields = ListField(max_length=1000, null=True)

    class Meta:
        unique_together = ('role', 'permission')


class AuthToken(BaseModel):
    pro_id = models.SmallIntegerField()
    user_id = models.BigIntegerField()
    token = models.CharField(max_length=100)

    class Meta:
        db_table = 'auth_token'
